package top.someapp.dxf2dsvg.jfx;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import top.someapp.dxf2dsvg.kits.Urls;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ResourceBundle;

/**
 * @author zwz
 * Created on 2020-04-27
 */
public class FxmlLoaderBuilder {
    private final String fxml;
    private FXMLLoader loader;
    private ResourceBundle resourceBundle;
    private JfxContext context;
    private boolean loaded;

    public FxmlLoaderBuilder(@Nonnull String fxml) {
        this.fxml = fxml;
        this.resourceBundle = I18N.getBundle();
        this.loader = new FXMLLoader(Urls.getResource(fxml));
    }

    public FxmlLoaderBuilder setResourceBundle(@Nonnull ResourceBundle resourceBundle) {
        this.resourceBundle = resourceBundle;
        return this;
    }

    public FxmlLoaderBuilder setContext(@Nonnull JfxContext context) {
        this.context = context;
        return this;
    }

    public static FxmlLoaderBuilder make(@Nonnull String fxml, @Nonnull JfxContext context) {
        return new FxmlLoaderBuilder(fxml).setContext(context);
    }

    public <T extends Node> T load() {
        T node = null;
        if (!loaded) {
            if (resourceBundle != null)
                loader.setResources(resourceBundle);
            
            try {
                node = loader.load();
                loaded = true;
                JfxController controller = loader.getController();
                if (controller != null) {
                    controller.onCreate(context);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return node;
    }

    public <C extends JfxController> C getController() {
        return loader.getController();
    }
}
